package com.advaita.licenseManager;

import javax.swing.JPanel;

import java.awt.BorderLayout;

import javax.swing.JTable;
import javax.swing.JLabel;

import java.awt.Font;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.swing.SwingConstants;

import com.advaita.license.Customer;
import com.advaita.xml.CustomerListHandler;

import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;

import java.awt.Color;

import javax.swing.JScrollPane;

public class CustomerList extends JPanel {
	private JTable table;
	private JScrollPane scrollPane;
	private String[][] custData;
	private ArrayList<Customer> custList;

	/**
	 * Create the panel.
	 */
	public CustomerList() {
		setLayout(new BorderLayout(0, 0));

		JLabel lblNewLabel = new JLabel("Customer Info");
		lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
		lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		add(lblNewLabel, BorderLayout.NORTH);

		String[] headers = { "Customer Name", "Exp Date" };
		custList = CustomerListHandler
				.readCustomerList();
		custData = new String[custList.size() + 1][2];

		for (int i = 0; i < custList.size(); i++) {
			custData[i][0] = custList.get(i).getUser();
			String date = new SimpleDateFormat("MM-dd-yyyy").format(custList.get(i).getLicenseInfo().getExpDate());
			custData[i][1] = date;
		}

		table = new JTable(custData, headers);
		table.setBorder(new LineBorder(new Color(0, 0, 0)));

		scrollPane = new JScrollPane(table);
		table.setFillsViewportHeight(true);
		add(scrollPane, BorderLayout.CENTER);
	}

	public Customer GetSelectedCustomer() {
		Customer cust = custList.get(table.getSelectedRow());
		return cust;
	}
	
	public void UpdateCustomer(Customer cust) {
		if (table.getSelectedRow() < 0){
			custList.add(cust);
		} else {
			Customer customer = GetSelectedCustomer();
			customer.setUser(cust.getUser());
			customer.setLicenseInfo(cust.getLicenseInfo());
		}
		CustomerListHandler.writeCustomerList(custList);
		
		/*custList = CustomerListHandler
				.readCustomerList();
		custData = new String[custList.size() + 1][2];

		for (int i = 0; i < custList.size(); i++) {
			custData[i][0] = custList.get(i).getUser();
			String date = new SimpleDateFormat("MM-dd-yyyy").format(custList.get(i).getLicenseInfo().getExpDate());
			custData[i][1] = date;
		}
		table.updateUI();
		table.invalidate();
		table.validate();
		table.repaint();*/
	}
}
